package com.foreknow.demo12;

import java.util.*;

public class Student implements Comparable<Student> {
    private Integer sid;
    private String name;
    private int age;

    public Student(String name,int age) {
        this.name = name;
        this.age = age;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    /**
     * 比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象，则分别返回负整数、零或正整数。
     * @param o 要比较的对象
     * @return int
     */
    @Override
    public int compareTo(Student o) {
        if(this.age > o.getAge()) {
            return 1;
        }else if(this.age < o.getAge()) {
            return -1;
        }else {
            return 0;
        }
    }

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        Student s1 = new Student("Test",58);
        Student s2 = new Student("Hum",28);
        Student s3 = new Student("Zhang",33);
        Student s4 = new Student("Marry",60);

        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        //对集合中的元素进行排序
        //        Collections.sort(list); //根据元素的自然顺序 对指定列表按升序进行排序。
        //        Iterator<Student> it = list.iterator();
        //        while (it.hasNext()) {
        //            Student student = it.next();
        //            System.out.println(student.getName() + "---" + student.getAge() );
        //        }

        //逆序输出
        //        Comparator comparator = Collections.reverseOrder();
        //        Collections.sort(list,comparator);
        //        Iterator<Student> it = list.iterator();
        //        while (it.hasNext()) {
        //            Student student = it.next();
        //            System.out.println(student.getName() + "---" + student.getAge() );
        //        }

        //根据姓名排序
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Iterator<Student> it = list.iterator();
        while (it.hasNext()) {
            Student student = it.next();
            System.out.println(student.getName());
        }
    }
}
